package com.navi.loaddata.loadService.impl.chamberHst;

import com.navi.loaddata.core.errorLog.ErrorCode;
import com.navi.loaddata.core.etlException.ETLException2;
import com.navi.loaddata.core.gpEntity.GpChipF;
import com.navi.loaddata.core.gpEntity.GpDefectF;
import com.navi.loaddata.core.mysqlEntity.EtlConfDModel;
import com.navi.loaddata.core.oracleEntity.*;
import com.navi.loaddata.core.util.LoggerUtil;
import com.navi.loaddata.core.util.ProcessUtil;
import com.navi.loaddata.loadDao.SaveBaseDataDao;
import com.navi.loaddata.loadDao.SaveFileDataDao;
import com.navi.loaddata.loadService.impl.baseData.LoadMesBaseDataService;
import org.apache.commons.collections.map.HashedMap;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author xufan
 */
@Service
//@Transactional(transactionManager = "thirdaryPlatformTransactionManager",
//        rollbackFor = {RuntimeException.class, Exception.class})
public class LoadChamberHstDataService {
    private static final Logger logger = LoggerFactory.getLogger(LoadChamberHstDataService.class);
    private LoggerUtil loggerUtil = new LoggerUtil(this.getClass());

    @Autowired
    private LoadMesBaseDataService loadMesBaseDataService;
    @Autowired
    private SaveBaseDataDao saveBaseDataDao;
    @Autowired
    private LoadChamberHstInfoService loadChamberHstInfoService;
    @Autowired
    private SaveChamberHst saveChamberHst;

    public String[] loadChamberHstDataMain(EtlConfDModel etlConfD) throws Exception {
        String[] resMsg = loadChamberHstData(etlConfD);
        String msg = etlConfD.getOpe();
        if (StringUtils.isEmpty(etlConfD.getOpe())) msg = "ALL";
        logger.info("OpeId={} loadChamberHstDataMain finish!", msg);
        return resMsg;
    }

    /**
     * Load Measure Data
     * <p>
     * load base -> session table
     * load defect data  -> session table
     * call base proc  -> auto commit
     * call defect proc -> no auto commit
     * delete defect session table
     *
     * @param etlConfD
     */
    private String[] loadChamberHstData(EtlConfDModel etlConfD) throws Exception {
        String[] resMsg = new String[3];
        int okCnt = 0;
        int errCnt = 0;
        String errMsg = null;
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        // get hst
        List<EtlChamberHstV> glassList = loadChamberHstInfoService.loadChamberHstInfo(etlConfD);
        logger.info("{} chamberHst glass count {}", etlConfD.getShop(), glassList.size());

        if (!glassList.isEmpty()) {
            int glassSize = glassList.size();
            // base
            List<EtlStepV> etlStepVList = loadMesBaseDataService.loadAllFinalStep(etlConfD.getShop());
            List<EtlProductV> etlProductVList = loadMesBaseDataService.loadAllFinalProduct(etlConfD.getShop());
            // save base and proc
            saveBaseDataDao.saveBaseData(etlConfD, etlStepVList, etlProductVList);

            //去重
            String key = "";
            for (int i = 0; i < glassSize; i += 1000) {
                Map<String, EtlChamberHstV> saveList = new HashedMap();
                for (int j = 0; j < 1000; j++) {
                    if (i + j < glassSize) {
                        key = glassList.get(i + j).getStepId() + "_" + glassList.get(i + j).getGlassId() + "_" +
                                glassList.get(i + j).getChipId() + "_" + glassList.get(i + j).getChipNo() + "_" +
                                glassList.get(i + j).getGlassEndTime() + "_" + glassList.get(i + j).getEquipId() + "_" +
                                glassList.get(i + j).getSubEquipId();
                        if (ProcessUtil.opeLimit(glassList.get(i + j).getStepId())) {
                            logger.warn(key + " 站点信息不符合规范。跳过!");
                            errCnt++;
                            continue;
                        }
                        if (!"A".equals(glassList.get(i + j).getGlassId().substring(0, 1)) && !"C".equals(glassList.get(i + j).getGlassId().substring(0, 1))) {
                            logger.warn(key + " GLASS_ID 信息不符合规范。跳过!");
                            errCnt++;
                            continue;
                        }
                        if (saveList.size() > 0 && null != saveList.get(key)) {
                            logger.warn(key + " 数据主键重复。跳过!");
                            errCnt++;
                            continue;
                        }
                        saveList.put(key, glassList.get(i + j));
                        okCnt++;
//                        logger.info("glassId={} opeId={} chipId={} chipNo={} glassEndTime={} lineId={} eqptId={} 转换成功",
//                                glassList.get(i + j).getGlassId(), glassList.get(i + j).getStepId(),
//                                glassList.get(i + j).getChipId(), glassList.get(i + j).getChipNo(),
//                                glassList.get(i + j).getGlassEndTime(), glassList.get(i + j).getEquipId(),
//                                glassList.get(i + j).getSubEquipId());
                    }
                }
                saveChamberHst.deleteChamberHstList1000(etlConfD);
                saveChamberHst.saveChamberHstList1000(etlConfD, saveList);
//                logger.info("success:{}",i);
            }


        } else {
            logger.info("没有此区间的数据。"); // todo print log & save etl data
        }
        resMsg[0] = String.valueOf(okCnt);
        resMsg[1] = String.valueOf(errCnt);
        resMsg[2] = errMsg;

        return resMsg;
    }


}
